module game
{
	export class GameManager
	{
		private static _instance: GameManager;

		public constructor()
		{
		}

		public static getInstance(): GameManager
		{
			if (this._instance == null)
			{
				this._instance = new GameManager();
			}

			return this._instance;
		}

		public upload_map(data: any, callBack: Function, thisObj: any): void
		{
			let xhr = new XMLHttpRequest();
			let xhrUrl = GlobalData.serverUrl +"map/upload?acc=" + GlobalData.accData.acc;
			xhr.open("POST", xhrUrl, true);
			xhr.onload = () =>
			{
				if (xhr.status == 200)
				{
					console.warn("upload_map", xhr.responseText);
					let obj = JSON.parse(xhr.responseText);
					GlobalData.mapId = obj.mapid;
					callBack.call(thisObj);
				}
				else if (xhr.status > 0)
				{
					this.onGetError(xhr.responseText);
				}
			}
			let body = JSON.stringify(data);
			xhr.send(body);
		}
		/**网络请求失败 */
		private onGetError(e)
		{
			console.warn("网络请求失败:" + e);
		}

		public login(acc: string, callBack: Function, thisObj: any): void
		{
			let xhr = new XMLHttpRequest();
			let xhrUrl = GlobalData.serverUrl +"login?acc=" + acc;
			xhr.open("GET", xhrUrl, true);
			xhr.onload = () =>
			{
				if (xhr.status == 200)
				{
					console.warn("login", xhr.responseText);
					let obj = JSON.parse(xhr.responseText);
					GlobalData.accData = obj;
					callBack.call(thisObj);
				}
				else if (xhr.status > 0)
				{
					this.onGetError(xhr.responseText);
				}
			}

			xhr.send();
		}

		public getMapById(id: string, callBack: Function, thisObj: any):void
		{
			let xhr = new XMLHttpRequest();
			let xhrUrl = GlobalData.serverUrl +"map?mapid=" + id;
			xhr.open("GET", xhrUrl, true);
			xhr.onload = () =>
			{
				if (xhr.status == 200)
				{
					console.warn("getMapById", xhr.responseText);
					let obj = JSON.parse(xhr.responseText);
					GlobalData.mapData = obj;
					callBack.call(thisObj);
				}
				else if (xhr.status > 0)
				{
					this.onGetError(xhr.responseText);
				}
			}

			xhr.send();
		}

		public getMapByAcc(acc: string, callBack: Function, thisObj: any):void
		{
			let xhr = new XMLHttpRequest();
			let xhrUrl = GlobalData.serverUrl +"map?acc=" + acc;
			xhr.open("GET", xhrUrl, true);
			xhr.onload = () =>
			{
				if (xhr.status == 200)
				{
					console.warn("getMapByAcc", xhr.responseText);
					let obj = JSON.parse(xhr.responseText);
					GlobalData.mapData = obj;
					callBack.call(thisObj);
				}
				else if (xhr.status > 0)
				{
					this.onGetError(xhr.responseText);
				}
			}

			xhr.send();
		}

		public getAllParams():any
		{
			console.log("href:" + document.location.href);
			var url = document.location.href;
			var position = url.indexOf("?");
			var parameterStr = url.substr(position + 1);
			var arr = parameterStr.split("&");
			var obj = {};
			for (var i = 0; i < arr.length; i++)
			{
				var data = arr[i].split("=");
				obj[data[0]] = data[1];
			}
			return obj;
		}
	}
}